package indv.Cshen.cfengsecurityshirodemo.realm;

import indv.Cshen.cfengsecurityshirodemo.domain.ShiroUser;
import indv.Cshen.cfengsecurityshirodemo.service.ShiroUserService;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;
import org.springframework.context.annotation.Lazy;

import javax.annotation.Resource;

/**
 * @author Cfeng
 * @date 2022/7/21
 * 只需要有一个Realm进行授权即可，因为多个Realm时Shiro会自动查找带有授权的Realm进行授权，其他的realm只需要进行认证
 * 该Realm只是进行Mobile认证，继承AuthenticatingRealm即可，AuthorizingRealm是其子类，带有授权功能
 */

@Slf4j
@NoArgsConstructor //在配置文件中创建Realm
public class MobileRealm extends AuthenticatingRealm {
    @Lazy
    @Resource
    private ShiroUserService shiroUserService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("entered the method =========================" + this.getName() + ": doGetAuthenticationInfo");
        //获得用户token的手机号mobile
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //这里的mobile就是用户输入的之前的UserName
        String mobile = token.getUsername();
        ShiroUser user = shiroUserService.queryUserByMobile(mobile);
        if(user != null) {
            ByteSource salt = ByteSource.Util.bytes(user.getUserName());
            return new SimpleAuthenticationInfo(user,user.getUserPwd(),salt,this.getName());
        }
        return null;
    }
}
